const nodemailer = require('nodemailer');
const path = require('path');
const fs = require('fs').promises;
const { emailConfig, recipients } = require('../config/email');
const logger = require('../utils/logger');

class EmailService {
    constructor() {
        this.transporter = null;
        this.initializeTransporter();
    }

    async initializeTransporter() {
        try {
            this.transporter = nodemailer.createTransport(emailConfig);
            
            // 验证邮件配置
            await this.transporter.verify();
            logger.info('邮件服务初始化成功');
        } catch (error) {
            logger.error(`邮件服务初始化失败: ${error.message}`);
            throw error;
        }
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    generateSuccessEmailContent(backupResult) {
        const { fileName, size, tables, deletedOldFiles, timestamp } = backupResult;
        
        return {
            subject: `✅ 数据库备份成功 - ${new Date().toLocaleDateString('zh-CN')}`,
            html: `
                <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
                    <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 8px 8px 0 0;">
                        <h2 style="margin: 0; text-align: center;">🗄️ 数据库备份成功</h2>
                    </div>
                    
                    <div style="background: #f8f9fa; padding: 20px; border-radius: 0 0 8px 8px; border: 1px solid #dee2e6;">
                        <div style="background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                            <h3 style="color: #28a745; margin-top: 0;">✅ 备份详情</h3>
                            <table style="width: 100%; border-collapse: collapse;">
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #495057;">数据库名称:</td>
                                    <td style="padding: 8px 0; color: #6c757d;">${process.env.DB_NAME}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #495057;">备份文件:</td>
                                    <td style="padding: 8px 0; color: #6c757d;">${fileName}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #495057;">文件大小:</td>
                                    <td style="padding: 8px 0; color: #6c757d;">${this.formatFileSize(size)}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #495057;">表数量:</td>
                                    <td style="padding: 8px 0; color: #6c757d;">${tables} 个表</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #495057;">备份时间:</td>
                                    <td style="padding: 8px 0; color: #6c757d;">${new Date(timestamp).toLocaleString('zh-CN')}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #495057;">清理文件:</td>
                                    <td style="padding: 8px 0; color: #6c757d;">删除了 ${deletedOldFiles} 个旧备份文件</td>
                                </tr>
                            </table>
                        </div>
                        
                        <div style="background: #e7f3ff; padding: 15px; border-radius: 8px; border-left: 4px solid #007bff;">
                            <p style="margin: 0; color: #004085;">
                                <strong>📎 备份文件已作为附件发送</strong><br>
                                请妥善保存备份文件，建议定期检查备份完整性。
                            </p>
                        </div>
                    </div>
                    
                    <div style="text-align: center; margin-top: 20px; color: #6c757d; font-size: 12px;">
                        <p>此邮件由数据库备份系统自动发送 | ${new Date().toLocaleString('zh-CN')}</p>
                    </div>
                </div>
            `
        };
    }

    generateFailureEmailContent(error) {
        return {
            subject: `❌ 数据库备份失败 - ${new Date().toLocaleDateString('zh-CN')}`,
            html: `
                <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
                    <div style="background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%); color: white; padding: 20px; border-radius: 8px 8px 0 0;">
                        <h2 style="margin: 0; text-align: center;">⚠️ 数据库备份失败</h2>
                    </div>
                    
                    <div style="background: #f8f9fa; padding: 20px; border-radius: 0 0 8px 8px; border: 1px solid #dee2e6;">
                        <div style="background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                            <h3 style="color: #dc3545; margin-top: 0;">❌ 错误详情</h3>
                            <table style="width: 100%; border-collapse: collapse;">
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #495057;">数据库名称:</td>
                                    <td style="padding: 8px 0; color: #6c757d;">${process.env.DB_NAME}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #495057;">失败时间:</td>
                                    <td style="padding: 8px 0; color: #6c757d;">${new Date().toLocaleString('zh-CN')}</td>
                                </tr>
                                <tr>
                                    <td style="padding: 8px 0; font-weight: bold; color: #495057; vertical-align: top;">错误信息:</td>
                                    <td style="padding: 8px 0; color: #dc3545; font-family: monospace; background: #f8f9fa; padding: 10px; border-radius: 4px;">${error.message}</td>
                                </tr>
                            </table>
                        </div>
                        
                        <div style="background: #fff3cd; padding: 15px; border-radius: 8px; border-left: 4px solid #ffc107;">
                            <p style="margin: 0; color: #856404;">
                                <strong>🔧 建议检查项目:</strong><br>
                                • 数据库连接配置是否正确<br>
                                • 数据库服务是否正常运行<br>
                                • 磁盘空间是否充足<br>
                                • 用户权限是否足够
                            </p>
                        </div>
                    </div>
                    
                    <div style="text-align: center; margin-top: 20px; color: #6c757d; font-size: 12px;">
                        <p>此邮件由数据库备份系统自动发送 | ${new Date().toLocaleString('zh-CN')}</p>
                    </div>
                </div>
            `
        };
    }

    async sendBackupSuccess(backupResult) {
        if (!recipients.length) {
            logger.warn('未配置收件人邮箱，跳过邮件发送');
            return { success: false, reason: 'No recipients configured' };
        }

        const emailContent = this.generateSuccessEmailContent(backupResult);
        
        try {
            // 检查备份文件是否存在
            await fs.access(backupResult.backupFile);
            
            const mailOptions = {
                from: `"数据库备份系统" <${emailConfig.auth.user}>`,
                to: recipients.join(', '),
                subject: emailContent.subject,
                html: emailContent.html,
                attachments: [
                    {
                        filename: backupResult.fileName,
                        path: backupResult.backupFile,
                        contentType: 'application/zip'
                    }
                ]
            };

            const info = await this.transporter.sendMail(mailOptions);
            logger.info(`备份成功邮件发送完成: ${info.messageId}`);
            logger.info(`收件人: ${recipients.join(', ')}`);
            
            return {
                success: true,
                messageId: info.messageId,
                recipients: recipients.length
            };
            
        } catch (error) {
            logger.error(`发送备份成功邮件失败: ${error.message}`);
            throw error;
        }
    }

    async sendBackupFailure(error) {
        if (!recipients.length) {
            logger.warn('未配置收件人邮箱，跳过邮件发送');
            return { success: false, reason: 'No recipients configured' };
        }

        const emailContent = this.generateFailureEmailContent(error);
        
        try {
            const mailOptions = {
                from: `"数据库备份系统" <${emailConfig.auth.user}>`,
                to: recipients.join(', '),
                subject: emailContent.subject,
                html: emailContent.html
            };

            const info = await this.transporter.sendMail(mailOptions);
            logger.info(`备份失败邮件发送完成: ${info.messageId}`);
            logger.info(`收件人: ${recipients.join(', ')}`);
            
            return {
                success: true,
                messageId: info.messageId,
                recipients: recipients.length
            };
            
        } catch (emailError) {
            logger.error(`发送备份失败邮件失败: ${emailError.message}`);
            throw emailError;
        }
    }

    async testConnection() {
        try {
            await this.transporter.verify();
            logger.info('邮件服务连接测试成功');
            return { success: true };
        } catch (error) {
            logger.error(`邮件服务连接测试失败: ${error.message}`);
            throw error;
        }
    }
}

module.exports = new EmailService(); 